<template>
	<div>
		<el-button class="uw-mb-10" type="primary" @click="showModel=true">添加分类</el-button>
		<uw-table :tableConfig="tableConfig">
			<template #button="{data,row}">
				<el-button v-for="item in data" :type="item.type" @click="handleButton(item,row)">{{item.label}}</el-button>
			</template>
		</uw-table>
		<uw-dialog title="添加分类" width="430px" v-model="showModel">
			<template #default>
				<uw-form ref="addFromRef" :show-btn="false" :data="addFromData">
					<uw-form-item :data="addFromData"></uw-form-item>
				</uw-form>
			</template>
			<template #footer>
				<el-button @click="showModel=false">关闭</el-button>
				<el-button type="primary" @click="tapSubmit">确定</el-button>
			</template>
		</uw-dialog>
	</div>
</template>

<script setup lang="ts">
	import { ref , onMounted , reactive } from 'vue';
	import { ElMessage , ElMessageBox } from 'element-plus';
	import { getCategoriesApi , createCategoryApi , deleteCategoryApi } from '@/api/article';//接口
	import { Article , ArticleCategory , tableConfigData } from '@/api/article'; // 接口字段定义
	const showModel = ref(false)
	const addFromRef = ref()
	const formInline = ref()
	const addFromData = reactive({
		inline:false,
		fields:[
			{
				label:'分类名称',
				type:'input',
				name:'name',
				value:'',
				placeholder:'请输入分类名称',
				width:'400px',
				rules:[
					{ required: true, message: '请输入分类名称', trigger: 'blur' }
				]
			}
		]
	})
	const tableConfig = reactive({
		border: false,
		data: [],
		columns: [
			{ label: 'ID', prop: 'id', align: 'center' },
			{ label: '分类名称', prop: 'name', align: 'center' },
			{ label: '创建时间', prop: 'createdAt', align: 'center' },
			{
				label: '操作',
				align: 'center',
				type: 'button',
				width: '200px',
				button: [
					{ label: '编辑', type: 'primary', value: 'deit' },
					{ label: '删除', type: 'danger', value: 'delete' }
				]
			}
		]
	})
	const getCategories = async () => {
		getCategoriesApi().then(({data})=>{
			tableConfig.data = data
		})
	}
	/**
	 * 搜索提交
	 */
	const serachSubmit = (data : any) => {
		console.log(data);
	}
	/**
	 * 操作按钮 
	 */
	const handleButton = (row:any,{id,name}) => {
		switch (row.value){
			case "deit":
				addFromData.fields[0].name = name
				showModel.value = true
				break;
			case "delete":
				ElMessageBox.confirm('此操作将永久删除该分类, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteCategoryApi(id).then(()=>{
						ElMessage.success('删除成功')
						getCategories()
					}).catch((err)=>{
						console.log(err);
					})
				}).catch(() => {})
				break;
			default:
				break;
		}
	}
	const tapSubmit = () => {
		const { name } = addFromRef.value.submit()
		if(!name) return ElMessage.error('分类名称不能为空')
		createCategoryApi(name).then(({data})=>{
			ElMessage.success('添加成功')
			showModel.value = false
			getCategories()
		}).catch((err)=>{
			console.log(err);
		})
	}
	onMounted(() => {
		getCategories()
	})
</script>

<style scoped>

</style>